//
//  PersonDataViewController.m
//  IpadTestB
//
//  Created by edianzu on 2017/6/30.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "PersonDataViewController.h"
#import "InputDataView.h"
@interface PersonDataViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)BaseAlertView * alertView;
@property(nonatomic,strong)InputDataView * inputDataView;
@property(nonatomic,assign)NSInteger lines;
@property(nonatomic,strong)NSNumber * changingId;
@property(nonatomic,strong)NSMutableDictionary * allDataDictionary;
@property(nonatomic,copy)NSString * belongClass;//所属班级
@property(nonatomic,strong)NSMutableArray * standByArr;//准备上传的数据
@end

@implementation PersonDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change:) name:UITextFieldTextDidChangeNotification object:self.inputDataView.inputTextField];//此处监听用于 输入数据时，有数据不让按钮可以点击
    // Do any additional setup after loading the view.
    self.title = @"个人数据";
    self.view.backgroundColor = UIColorFromRGB(241, 246, 248);
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont boldSystemFontOfSize:23*AutoScaleHorizontal],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    ////////////////左按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame = CGRectMake(0, 0, 35,35);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"navBack"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftBarBtn = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = 15;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarBtn];
    
    //创建右边按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 140,35);
    //    rightBtn.layer.cornerRadius =10;
    rightBtn.backgroundColor = [UIColor clearColor];
    //    [rightBtn setImage:[UIImage imageNamed:@"navRightBtn"] forState:UIControlStateNormal];
    [rightBtn setTitle:@"上传" forState:UIControlStateNormal];
    [rightBtn setImage:[UIImage imageNamed:@"upload"] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBarBtn = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItemm = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItemm.width = -5;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.rightBarButtonItems = @[spaceItemm,rightBarBtn];
    
    
    
    
    [self getData];
}

-(void)getData{
    self.dataArray = [[NSMutableArray alloc]init];
    
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    //获取全部数据
    NSString* str = [user objectForKey:@"AllData"];
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    NSMutableArray * testArray = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"TestResult"]];
    NSMutableArray * ClassArray = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"ClassList"]];
    //查找班级名称
    for (NSMutableDictionary*dic in ClassArray) {
        if ([[dic objectForKey:@"Id"]isEqual:self.model.ClassId]) {
            self.belongClass = [dic objectForKey:@"Name"];
        }
    }
    
    //添加测试项目
        for (NSDictionary * dict in testArray) {
            NSDictionary * masterdic = [dict objectForKey:@"master"];
            
            if ([[masterdic objectForKey:@"ChildId"]isEqual:self.model.Id]) {
                
                if ([[masterdic objectForKey:@"ProgramId"]isEqual:self.planmodel.Id]) {
                    
                    for (NSMutableDictionary * detailDic in [dict objectForKey:@"detailList"]) {
                        if (![[detailDic objectForKey:@"ProjectId"] isEqual:@3] && ![[detailDic objectForKey:@"ProjectId"] isEqual:@11]) {
                        DetailListModel * model = [DetailListModel modelWithDictionary:detailDic];
                        [self.dataArray addObject:model];
                        }
                    }
                   
                }
            }
        }
    
    //右侧需要多少行
    if (self.dataArray.count % 3 ==0) {
        self.lines = self.dataArray.count/3;
    }else{
        self.lines = self.dataArray.count/3 + 1;
    }
    [user synchronize];
    [self creatTop];
}


-(void)creatTop{
    //整个依赖SCRVIEW
    //整个依赖scrollview
    _myScrollView = [[UIScrollView alloc]init];
    _myScrollView.backgroundColor = UIColorFromRGB(241, 246, 248);
    _myScrollView.contentSize = CGSizeMake(0, 1000);
    _myScrollView.scrollEnabled =YES;
    _myScrollView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:_myScrollView];
    [_myScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.top.mas_equalTo(self.view.mas_top);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT));
    }];
    
    //上方白色背景
    self.topView = [[UIView alloc]init];
    self.topView.backgroundColor = [UIColor whiteColor];
    self.topView.layer.cornerRadius = 10;
    self.topView.layer.shadowColor=[[UIColor grayColor] colorWithAlphaComponent:0.8].CGColor;
    self.topView.layer.shadowOffset=CGSizeMake(10,10);
    self.topView.layer.shadowOpacity=0.5;
    self.topView.layer.shadowRadius=8;
    self.topView.layer.masksToBounds = YES;
    [self.myScrollView addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.myScrollView.mas_left).with.offset(75*AutoScaleHorizontal);
        //        make.right.mas_equalTo(self.myScrollView.mas_right).with.offset(-75*AutoScaleHorizontal);
        make.top.mas_equalTo(self.myScrollView.mas_top).with.offset(25*AutoScaleVertical);
        make.height.mas_equalTo(130*AutoScaleVertical);
        make.width.mas_equalTo(862*AutoScaleHorizontal);
    }];
    //姓名
    self.topNameLabel = [[UILabel alloc]init];
    self.topNameLabel.font = [UIFont boldSystemFontOfSize:25*AutoScaleHorizontal];
    self.topNameLabel.textColor = [UIColor blackColor];
    self.topNameLabel.text = self.model.ChildName;
//    NSDictionary *attrs = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:25*AutoScaleHorizontal]};
//    CGSize size=[self.topNameLabel.text sizeWithAttributes:attrs];
    CGSize maximumLabelSize = CGSizeMake(100, 9999);//labelsize的最大值
    //关键语句
    CGSize expectSize = [self.topNameLabel sizeThatFits:maximumLabelSize];
    [self.myScrollView addSubview:self.topNameLabel];
    [self.topNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.topView.mas_left).with.offset(45*AutoScaleHorizontal);
        make.top.mas_equalTo(self.topView.mas_top).with.offset(30*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(expectSize.width, 30*AutoScaleVertical));
    }];
   

    //性别
    self.genderIMG = [[UIImageView alloc]init];
    if ([self.model.Gender isEqual:@1]) {
        self.genderIMG.image = [UIImage imageNamed:@"manIMGS"];
    }else{
        self.genderIMG.image = [UIImage imageNamed:@"womenIMGS"];
    }
    [self.topView addSubview:self.genderIMG];
    [self.genderIMG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.topNameLabel.mas_right).with.offset(20*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.topNameLabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(22*AutoScaleHorizontal, 22*AutoScaleVertical));
    }];
    
    //计划名
    self.planNameLabel = [[UILabel alloc]init];
    self.planNameLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    self.planNameLabel.textColor = [UIColor blackColor];
    self.planNameLabel.text =[NSString stringWithFormat:@"当前计划: %@",self.planmodel.Title] ;
    [self.myScrollView addSubview:self.planNameLabel];
    [self.planNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.genderIMG.mas_right).with.offset(55*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.genderIMG.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(550*AutoScaleHorizontal, 25*AutoScaleVertical));
    }];
    
    
   
    //班级
    self.classLabel = [[UILabel alloc]init];
    self.classLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    self.classLabel.textColor = [UIColor blackColor];
    self.classLabel.text = @"所属班级:";
    NSDictionary *attr = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:25*AutoScaleHorizontal]};
    CGSize sizee=[self.classLabel.text sizeWithAttributes:attr];
    [self.myScrollView addSubview:self.classLabel];
    [self.classLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.topView.mas_left).with.offset(45*AutoScaleHorizontal);
        make.top.mas_equalTo(self.topNameLabel.mas_bottom).with.offset(25*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(sizee.width, 25*AutoScaleVertical));
    }];
    
    self.classNameLabel = [[UILabel alloc]init];
    self.classNameLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    self.classNameLabel.textColor = [UIColor blackColor];
    if (self.belongClass !=nil) {
        self.classNameLabel.text = self.belongClass;
    }else{
        self.classNameLabel.text = @"无";
    }
    
    
    [self.myScrollView addSubview:self.classNameLabel];
    [self.classNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.classLabel.mas_right);
        make.top.mas_equalTo(self.topNameLabel.mas_bottom).with.offset(25*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, 25*AutoScaleVertical));
    }];
    
    //生日
    self.birthLabel = [[UILabel alloc]init];
    self.birthLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    self.birthLabel.textColor = [UIColor blackColor];
    self.birthLabel.text = @"生日:";
    NSDictionary *attr2 = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:25*AutoScaleHorizontal]};
    CGSize sizee2=[self.birthLabel.text sizeWithAttributes:attr2];
    [self.myScrollView addSubview:self.birthLabel];
    [self.birthLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.topView.mas_left).with.offset(365*AutoScaleHorizontal);
        make.top.mas_equalTo(self.topNameLabel.mas_bottom).with.offset(25*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(sizee2.width, 25*AutoScaleVertical));
    }];
    
    self.birthNameLabel = [[UILabel alloc]init];
    self.birthNameLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    self.birthNameLabel.textColor = [UIColor blackColor];
    self.birthNameLabel.text = [self.model.Birthday substringWithRange:NSMakeRange(0, 10)];
    [self.myScrollView addSubview:self.birthNameLabel];
    [self.birthNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.birthLabel.mas_right);
        make.top.mas_equalTo(self.topNameLabel.mas_bottom).with.offset(25*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(130*AutoScaleHorizontal, 25*AutoScaleVertical));
    }];
    
    //家长电话
    self.phoneLabel = [[UILabel alloc]init];
    self.phoneLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    self.phoneLabel.textColor = [UIColor blackColor];
    self.phoneLabel.text = @"家长电话:";
    NSDictionary *attr3 = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:25*AutoScaleHorizontal]};
    CGSize sizee3=[self.phoneLabel.text sizeWithAttributes:attr3];
    [self.myScrollView addSubview:self.phoneLabel];
    [self.phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.topView.mas_left).with.offset(590*AutoScaleHorizontal);
        make.top.mas_equalTo(self.topNameLabel.mas_bottom).with.offset(25*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(sizee3.width, 25*AutoScaleVertical));
    }];
    
    self.phoneNameLabel = [[UILabel alloc]init];
    self.phoneNameLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    self.phoneNameLabel.textColor = [UIColor blackColor];
    if (self.model.Phone == nil || self.model.Phone.length ==0) {
        
         self.phoneNameLabel.text = @"无";
    }else{
       self.phoneNameLabel.text = self.model.Phone;
    }
    [self.myScrollView addSubview:self.phoneNameLabel];
    [self.phoneNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.phoneLabel.mas_right);
        make.top.mas_equalTo(self.topNameLabel.mas_bottom).with.offset(25*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(150*AutoScaleHorizontal, 25*AutoScaleVertical));
    }];
        
    [self creatBottom];
}

//创建下方视图
-(void)creatBottom{
    NSLog(@"self.lines = %d",self.lines);
    
    self.bottomView = [[UIView alloc]init];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    self.bottomView.layer.cornerRadius = 10;
    self.bottomView.layer.shadowColor=[[UIColor grayColor] colorWithAlphaComponent:0.8].CGColor;
    self.bottomView.layer.shadowOffset=CGSizeMake(10,10);
    self.bottomView.layer.shadowOpacity=0.5;
    self.bottomView.layer.shadowRadius=8;
    self.bottomView.layer.masksToBounds = YES;
    [self.myScrollView addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.myScrollView.mas_left).with.offset(75*AutoScaleHorizontal);
        make.top.mas_equalTo(self.topView.mas_bottom).with.offset(15*AutoScaleVertical);
        make.height.mas_equalTo((155+100*self.lines+15 * (self.lines-1))*AutoScaleVertical);
        make.width.mas_equalTo(862*AutoScaleHorizontal);
    }];
    
    self.testDataLabel = [[UILabel alloc]init];
    self.testDataLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    self.testDataLabel.textColor = [UIColor blackColor];
    self.testDataLabel.text = @"测试数据";
    [self.bottomView addSubview:self.testDataLabel];
    [self.testDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.bottomView.mas_left).with.offset(45*AutoScaleHorizontal);
        make.top.mas_equalTo(self.bottomView.mas_top).with.offset(30*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(300, 25*AutoScaleVertical));
    }];
    
    self.testDataChangedLabel = [[UILabel alloc]init];
    self.testDataChangedLabel.font = [UIFont systemFontOfSize:18*AutoScaleHorizontal];
    self.testDataChangedLabel.textColor = UIColorFromRGB(206, 48, 0);
    self.testDataChangedLabel.text = @"测试数据已改变,请及时上传";
    NSDictionary *attr = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal]};
    CGSize size1=[self.testDataChangedLabel.text sizeWithAttributes:attr];
    [self.bottomView addSubview:self.testDataChangedLabel];
    [self.testDataChangedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.testDataLabel.mas_left);
        make.top.mas_equalTo(self.testDataLabel.mas_bottom).with.offset(15*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(size1.width, 25*AutoScaleVertical));
    }];
    self.testDataChangedLabel.hidden =YES;
    //循环创建项目小图标
    int a = 0 ;
    for (DetailListModel * model in self.dataArray) {
//        if (![model.ProjectId isEqual:@3] && ![model.ProjectId isEqual:@11]) {
            //依赖VIEW
            UIView * view = [[UIView alloc]init];
            view.layer.cornerRadius =10;
            view.layer.borderWidth= 1;
            view.layer.borderColor = UIColorFromRGB(218, 218, 218).CGColor;
            view.backgroundColor=[UIColor whiteColor];
            [self.bottomView addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self.bottomView.mas_left).with.offset((60+260*(a%3))*AutoScaleHorizontal);
                make.top.mas_equalTo(self.testDataChangedLabel.mas_bottom).with.offset((30+120*(a/3)*AutoScaleVertical));
                make.size.mas_equalTo(CGSizeMake(230*AutoScaleHorizontal, 100*AutoScaleVertical));
            }];
            //项目图片
            UIImageView * imageView = [[UIImageView alloc]init];
            imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"Image-%@",model.ProjectId]];
            [view addSubview:imageView];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(view.mas_left).with.offset(25*AutoScaleHorizontal);
                make.centerY.mas_equalTo(view.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(50*AutoScaleHorizontal, 50*AutoScaleVertical));
            }];
            
            //项目名称
            UILabel * label = [[UILabel alloc]init];
            label.textColor = [UIColor blackColor];
            label.numberOfLines = 2;
            label.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
            label.text = model.Name;
            [view addSubview: label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(view.mas_top).with.offset(7*AutoScaleVertical);
                make.left.mas_equalTo(imageView.mas_right).with.offset(15*AutoScaleHorizontal);
                make.size.mas_equalTo(CGSizeMake(100*AutoScaleHorizontal, 50*AutoScaleVertical));
            }];
            //项目结果
            UILabel * resultLabel = [[UILabel alloc]init];
            resultLabel.textColor = [UIColor blackColor];
            resultLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
            [view addSubview:resultLabel];
            [resultLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(label.mas_left);
                make.top.mas_equalTo(label.mas_bottom).with.offset(10*AutoScaleVertical);
                make.size.mas_equalTo(CGSizeMake(100*AutoScaleHorizontal, 20*AutoScaleVertical));
            }];
            //区分单位
            NSString * unit = [[NSString alloc]init];
            switch ([model.ProjectId integerValue]) {
                case 1:
                    unit = @"厘米";
                    break;
                case 2:
                    unit = @"千克";
                    break;
                case 4:
                    unit = @"圈";
                    break;
                case 5:
                    unit = @"个";
                    break;
                case 6:
                    unit = @"";
                    break;
                case 7:
                    unit = @"个";
                    break;
                case 8:
                    unit = @"厘米";
                    break;
                case 9:
                    unit = @"厘米";
                    break;
                case 10:
                    unit = @"秒";
                    break;
                default:
                    break;
            }
        if ([model.ProjectId  isEqual: @8]) {
            if (model.IsTest ==true) {
                resultLabel.text = @"无法测试";
            }else if ([model.Result isEqual:@-111]) {
                resultLabel.text = @"未测试";
                resultLabel.textColor =[UIColor redColor];
            }else if (model.Result == nil || [model.Result isEqual:@0]){
                resultLabel.text =[NSString stringWithFormat:@"0%@",unit];
                //                resultLabel.textColor =[UIColor redColor];
            }
            else{
                resultLabel.text = [NSString stringWithFormat:@"%@%@",model.Result,unit];
            }
        }else{
            if (model.IsTest ==true) {
                resultLabel.text = @"无法测试";
            }else if (model.Result == nil || [model.Result isEqual:@0]){
                resultLabel.text =[NSString stringWithFormat:@"0%@",unit];
                //                resultLabel.textColor =[UIColor redColor];
            }else{
                resultLabel.text = [NSString stringWithFormat:@"%@%@",model.Result,unit];
            }
        }
        
            //箭头
            UIImageView * arrow = [[UIImageView alloc]init];
            arrow.image = [UIImage imageNamed:@"arrowImage"];
            [view addSubview:arrow];
            [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(view.mas_right).with.offset(-10*AutoScaleHorizontal);
                make.centerY.mas_equalTo(view.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(15*AutoScaleHorizontal, 15*AutoScaleVertical));
            }];
            
            //覆盖按钮
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button addTarget:self action:@selector(touchInput:) forControlEvents:UIControlEventTouchUpInside];
            button.backgroundColor =[UIColor clearColor];
            button.tag = [model.ProjectId integerValue] + 100;
            [view addSubview:button];
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.bottom.mas_equalTo(view);
            }];
            
            
        
        a++;
    }

    self.myScrollView.contentSize = CGSizeMake(0, 295+100*self.lines+15 * (self.lines-1)*AutoScaleVertical);
}
#pragma mark 创建输入框
-(void)touchInput:(UIButton*)sender{
    
    
    _changingId = @(sender.tag- 100);
    NSLog(@"%@",_changingId);
    DetailListModel * model = [[DetailListModel alloc]init];
    for (DetailListModel * mod in self.dataArray) {
        if ([mod.ProjectId isEqual:_changingId]) {
            model = mod;
        }
    }
    //蒙版
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.52;
    [window addSubview:_backView];
    
    self.inputDataView = [[InputDataView alloc]init];
    self.inputDataView.childName.text = self.model.ChildName;
    self.inputDataView.projectLabel.text = model.Name;
    self.inputDataView.inputTextField.delegate =self;
    //区分单位
    switch ([model.ProjectId integerValue]) {
        case 1:
            self.inputDataView.unitLabel.text = @"厘米";
            break;
        case 2:
            self.inputDataView.unitLabel.text = @"千克";
            break;
        case 4:
            self.inputDataView.unitLabel.text = @"圈";
            break;
        case 5:
            self.inputDataView.unitLabel.text = @"个";
            break;
        case 6:
            self.inputDataView.unitLabel.text = @"";
            break;
        case 7:
            self.inputDataView.unitLabel.text = @"个";
            break;
        case 8:
            self.inputDataView.unitLabel.text = @"厘米";
            break;
        case 9:
            self.inputDataView.unitLabel.text = @"厘米";
            break;
        case 10:
            self.inputDataView.unitLabel.text = @"秒";
            break;
        default:
            break;
    }
    //结果
//    if (model.IsTest ==YES) {
//        self.inputDataView.unTestableBtn.selected = YES;
//        self.inputDataView.projectLabel.textColor = UIColorFromRGB(167, 167, 167);
//        self.inputDataView.unitLabel.textColor =UIColorFromRGB(167, 167, 167);
//        self.inputDataView.inputTextField.userInteractionEnabled =NO;
//        self.inputDataView.unTestableBtn.userInteractionEnabled = YES;
//        self.inputDataView.unTestableLabel.textColor = [UIColor blackColor];
//        self.inputDataView.starLabel.textColor = UIColorFromRGB(167, 167, 167);
//        
//    }else{
//        self.inputDataView.projectLabel.textColor = [UIColor blackColor];
//        self.inputDataView.unitLabel.textColor =[UIColor blackColor];
//        self.inputDataView.starLabel.textColor = [UIColor redColor];
//        self.inputDataView.inputTextField.userInteractionEnabled =YES;
//        self.inputDataView.unTestableLabel.textColor = UIColorFromRGB(167, 167, 167);
//        self.inputDataView.unTestableBtn.userInteractionEnabled = NO;
//        
//        if ([model.Result isEqual:@0]||model.Result == nil) {
//            self.inputDataView.inputTextField.text = @"0";
//        }else{
//            self.inputDataView.inputTextField.text =[NSString stringWithFormat:@"%@",model.Result];
//        }
//    }
    
    [self.inputDataView.unTestableBtn addTarget:self action:@selector(touchUnTestable) forControlEvents:UIControlEventTouchUpInside];
    [self.inputDataView.cancelBtn addTarget:self action:@selector(touchCancel) forControlEvents:UIControlEventTouchUpInside];
    [self.inputDataView.confirmBtn addTarget:self action:@selector(touchConfirm) forControlEvents:UIControlEventTouchUpInside];
    [window addSubview:self.inputDataView];
    [self.inputDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(window.mas_centerX);
        make.centerY.mas_equalTo(window.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(550*AutoScaleHorizontal, 300*AutoScaleVertical));
    }];
    
}
-(void)touchUnTestable{
    self.inputDataView.unTestableBtn.selected = !self.inputDataView.unTestableBtn.selected;
    if (self.inputDataView.unTestableBtn.selected ==YES) {
        self.inputDataView.projectLabel.textColor = UIColorFromRGB(167, 167, 167);
        self.inputDataView.unitLabel.textColor =UIColorFromRGB(167, 167, 167);
        self.inputDataView.inputTextField.userInteractionEnabled =NO;
        self.inputDataView.starLabel.textColor = UIColorFromRGB(167, 167, 167);
    }else{
        self.inputDataView.projectLabel.textColor = [UIColor blackColor];
        self.inputDataView.unitLabel.textColor =[UIColor blackColor];
        self.inputDataView.starLabel.textColor = [UIColor redColor];
        self.inputDataView.inputTextField.userInteractionEnabled =YES;
    }
}

-(void)touchCancel{
    [self.backView removeFromSuperview];
    [self.inputDataView removeFromSuperview];
}
//确认修改
-(void)touchConfirm{
    
    
    if (self.inputDataView.unTestableBtn.selected == NO && self.inputDataView.inputTextField.text.length==0) {
        [self.inputDataView.inputTextField resignFirstResponder];
        [self showMessage:@"请输入测试数据"];
    }else if([self.changingId isEqual:@1]){
        if (([self.inputDataView.inputTextField.text integerValue]<50 || [self.inputDataView.inputTextField.text integerValue]>200)&&self.inputDataView.unTestableBtn.selected == NO) {
            [self showMessage:@"当前项目取值范围是50～200厘米"];
            [self.inputDataView.inputTextField resignFirstResponder];
        }else{
            [self touchConFirmRight];
        }
    }else if([self.changingId isEqual:@2]){
        if (([self.inputDataView.inputTextField.text integerValue]<5 || [self.inputDataView.inputTextField.text integerValue]>100)&&self.inputDataView.unTestableBtn.selected == NO) {
            [self showMessage:@"当前项目取值范围是5～100千克"];
            [self.inputDataView.inputTextField resignFirstResponder];
        }else{
            [self touchConFirmRight];
        }
    }else if([self.changingId isEqual:@4]){
        if (([self.inputDataView.inputTextField.text integerValue]<=0 || [self.inputDataView.inputTextField.text integerValue]>207)&&self.inputDataView.unTestableBtn.selected == NO) {
            [self showMessage:@"当前项目取值范围是0～207圈"];
            [self.inputDataView.inputTextField resignFirstResponder];
        }else{
            [self touchConFirmRight];
        }
    }else if([self.changingId isEqual:@5]){
        if (([self.inputDataView.inputTextField.text integerValue]<=0 || [self.inputDataView.inputTextField.text integerValue]>75)&&self.inputDataView.unTestableBtn.selected == NO) {
            [self showMessage:@"当前项目取值范围是0～75个"];
            [self.inputDataView.inputTextField resignFirstResponder];
        }else{
            [self touchConFirmRight];
        }
    }else if([self.changingId isEqual:@6]){
        if (([self.inputDataView.inputTextField.text integerValue]<=0 || [self.inputDataView.inputTextField.text integerValue]>12)&&self.inputDataView.unTestableBtn.selected == NO) {
            [self showMessage:@"当前项目取值范围是0～12"];
            [self.inputDataView.inputTextField resignFirstResponder];
        }else{
            [self touchConFirmRight];
        }
    }else if([self.changingId isEqual:@7]){
        if (([self.inputDataView.inputTextField.text integerValue]<=0 || [self.inputDataView.inputTextField.text integerValue]>100)&&self.inputDataView.unTestableBtn.selected == NO) {
            [self showMessage:@"当前项目取值范围是0～100个"];
            [self.inputDataView.inputTextField resignFirstResponder];
        }else{
            [self touchConFirmRight];
        }
    }else if([self.changingId isEqual:@8]){
        if (([self.inputDataView.inputTextField.text integerValue]<-20 || [self.inputDataView.inputTextField.text integerValue]>40)&&self.inputDataView.unTestableBtn.selected == NO) {
            [self showMessage:@"当前项目取值范围是-20～40厘米"];
            [self.inputDataView.inputTextField resignFirstResponder];
        }else{
            [self touchConFirmRight];
        }
    }else if([self.changingId isEqual:@9]){
        if (([self.inputDataView.inputTextField.text integerValue]<20 || [self.inputDataView.inputTextField.text integerValue]>320)&&self.inputDataView.unTestableBtn.selected == NO) {
            [self showMessage:@"当前项目取值范围是20～320厘米"];
            [self.inputDataView.inputTextField resignFirstResponder];
        }else{
            [self touchConFirmRight];
        }
    }else if([self.changingId isEqual:@10]){
        if (([self.inputDataView.inputTextField.text integerValue]<2 || [self.inputDataView.inputTextField.text integerValue]>60)&&self.inputDataView.unTestableBtn.selected == NO) {
            [self showMessage:@"当前项目取值范围是2～60秒"];
            [self.inputDataView.inputTextField resignFirstResponder];
        }else{
            [self touchConFirmRight];
        }
    }
}
//没有超出范围
-(void)touchConFirmRight{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    {
        //修改数值
        DetailListModel * changeModel = [[DetailListModel alloc]init];//用来跟数据源比较判断是否做了修改
        for (DetailListModel * mod in self.dataArray) {
            if ([mod.ProjectId isEqual:self.changingId]) {
                if (self.inputDataView.unTestableBtn.selected ==YES) {
                    mod.IsTest = YES;
                }else{
                    mod.IsTest = NO;
                    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
                    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
                    NSNumber *numTemp = [numberFormatter numberFromString:self.inputDataView.inputTextField.text];
                    mod.Result =  numTemp;
                    
                }
                changeModel = mod;
            }
            
        }
        
        //与数据源做对比 看是否有改变
        NSInteger isChanged = 0;
        
        //获取全部数据
        NSString* str = [user objectForKey:@"AllData"];
        //    NSLog(@"eee===%@",str);
        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * startDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray * testArray = [NSMutableArray arrayWithArray: [startDic objectForKey:@"TestResult"]];
        for (NSDictionary * dict in testArray) {
            NSDictionary * masterdic = [dict objectForKey:@"master"];
            
            if ([[masterdic objectForKey:@"ChildId"]isEqual:self.model.Id]) {
                
                if ([[masterdic objectForKey:@"ProgramId"]isEqual:self.planmodel.Id]) {
                    
                    for (NSMutableDictionary * detailDic in [dict objectForKey:@"detailList"]) {
                        if ([[detailDic objectForKey:@"ProjectId"]isEqual:self.changingId]) {
                            
                            if (changeModel.IsTest) {
                                if (![[detailDic objectForKey:@"IsTest"]boolValue]) {
                                    isChanged +=1;
                                    
                                }
                            }
                            
                            if (!changeModel.IsTest) {
                                if ([[detailDic objectForKey:@"IsTest"]boolValue]) {
                                    isChanged +=1;
                                }
                            }
                            
                            if (![changeModel.Result isEqual:[detailDic objectForKey:@"Result"]]) {
                                isChanged +=1;
                            }
                            
                        }
                    }
                    
                }
            }
        }
        
        
        
        [self.bottomView removeFromSuperview];
        [self creatBottom];
        if (isChanged == 0) {
            self.testDataChangedLabel.hidden =YES;
        }else{
            self.testDataChangedLabel.hidden =NO;
        }
        
        //更新待上传数据
        _standByArr = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"TestResult"]];
        for (NSDictionary * dict in _standByArr) {
            NSDictionary * masterdic = [dict objectForKey:@"master"];
            
            if ([[masterdic objectForKey:@"ChildId"]isEqual:self.model.Id]) {
                
                if ([[masterdic objectForKey:@"ProgramId"]isEqual:self.planmodel.Id]) {
                    
                    for (NSMutableDictionary * detailDic in [dict objectForKey:@"detailList"]) {
                        if ([[detailDic objectForKey:@"ProjectId"]isEqual:self.changingId]) {
                            if (changeModel.IsTest) {
                                NSNumber *boolNumber = [NSNumber numberWithBool:YES];
                                //判断此项result change ，是， 给一个VALUECHANGE字段
                                if (![[detailDic objectForKey:@"IsTest"]boolValue] ) {
                                    [detailDic setObject:@"1" forKey:@"1900V"];
                                }
                                [detailDic setObject:boolNumber forKey:@"IsTest"];
                            }else{
                                NSNumber *boolNumber = [NSNumber numberWithBool:NO];
                                //判断此项result change ，是， 给一个VALUECHANGE字段
                                if ([[detailDic objectForKey:@"IsTest"]boolValue] ) {
                                    [detailDic setObject:@"1" forKey:@"1900V"];
                                }
                                [detailDic setObject:boolNumber forKey:@"IsTest"];
                            }
                            if (changeModel.Result == nil) {
                                [detailDic setObject:@0 forKey:@"Result"];
                            }else{
                                //判断此项result change ，是， 给一个VALUECHANGE字段
                                if (![[detailDic objectForKey:@"Result"] isEqual:changeModel.Result] ) {
                                    [detailDic setObject:@"1" forKey:@"1900V"];
                                }
                                [detailDic setObject:changeModel.Result forKey:@"Result"];
                            }
                        }
                    }
                }
            }
        }
        //
        [_allDataDictionary removeObjectForKey:@"TestResult"];
        [_allDataDictionary setObject:_standByArr forKey:@"TestResult"];
        NSData * data = [NSJSONSerialization dataWithJSONObject:_allDataDictionary options:NSJSONWritingPrettyPrinted error:nil];
        NSString * allStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //
        [user removeObjectForKey:@"AllData"];
        [user setObject:allStr forKey:@"AllData"];
        [user setObject:@"yes" forKey:@"ValueChanged"];
        [user synchronize];
        
        [self.backView removeFromSuperview];
        [self.inputDataView removeFromSuperview];
    }

}

#pragma mark 左右导航栏按钮方法
-(void)leftBarBtnClicked{
    NSLog(@"左按钮");
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 上传
-(void)rightBarBtnClicked{
    NSLog(@"右按钮");
    [self uploadData];
//    //蒙版
//    UIWindow * window = [UIApplication sharedApplication].keyWindow;
//    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
//    _backView.backgroundColor = [UIColor blackColor];
//    _backView.alpha = 0.52;
//    [window addSubview:_backView];
//    
//    self.alertView = [[BaseAlertView alloc]init];
//    [window addSubview:self.alertView];
//    [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(window.mas_centerX);
//        make.centerY.mas_equalTo(window.mas_centerY);
//        make.size.mas_equalTo(CGSizeMake(500*AutoScaleHorizontal, 250*AutoScaleVertical));
//    }];
//    self.alertView.infomationLabel.text = @"测试数据已修改，是否现在上传？";
////    self.alertView.remindLabel.text = @"提醒";
//    [self.alertView.yesBtn addTarget:self action:@selector(pressAlertYes) forControlEvents:UIControlEventTouchUpInside];
//    [self.alertView.noBtn addTarget:self action:@selector(pressAlertNo) forControlEvents:UIControlEventTouchUpInside];
    
}

//-(void)pressAlertYes{
//    NSLog(@"确定");
//    [_backView removeFromSuperview];
//    [self.alertView removeFromSuperview];
//    [self uploadData];
//    
//
//
//}
//-(void)pressAlertNo{
//    NSLog(@"取消");
//    [_backView removeFromSuperview];
//    [self.alertView removeFromSuperview];
//}
//text智能输入数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if ([self.changingId isEqual:@4] || [self.changingId isEqual:@5]||[self.changingId isEqual:@7]) {
        return [self validateNumberWithDouHao:string];
    }else{
        return [self validateNumber:string];
    }
}
//可以输入逗号
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@".-0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}
//不能输入逗号
- (BOOL)validateNumberWithDouHao:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"-0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

//TEXTfield有数据时  按钮不可点击
-(void)change:(NSNotification *)notification
{
    if (self.inputDataView.inputTextField.text.length > 0) {
        self.inputDataView.unTestableBtn.userInteractionEnabled = NO;
        self.inputDataView.unTestableLabel.textColor = UIColorFromRGB(167, 167, 167);
        self.inputDataView.unTestableBtn.alpha = 0.3;
        
    }else
    {
        self.inputDataView.unTestableBtn.userInteractionEnabled = YES;
        self.inputDataView.unTestableLabel.textColor = [UIColor blackColor];
        self.inputDataView.unTestableBtn.alpha = 1;
    }
    
}


// 释放
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    
}
#pragma mark 同步数据
-(void)uploadData{
    
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    //拿到本地数据
    NSMutableArray * localChildListArray = [_allDataDictionary objectForKey:@"ChildList"];
    NSMutableArray * localClassListArray = [_allDataDictionary objectForKey:@"ClassList"];
    NSMutableArray * localProgramsArray = [_allDataDictionary objectForKey:@"Programs"];
    NSMutableArray * localTestResultArray = [_allDataDictionary objectForKey:@"TestResult"];
    //遍历得到需要上传的数据
    //*****************************agencyid////////////////////////////////////////////////////////////////////
    NSInteger  agencyId = [[user objectForKey:@"AgencyId"]integerValue];
    //agencyid////////////////////////////////////////////////////////////////////
    
    //*****************************删除的对象////////////////////////////////////////////////////////////////////
    NSMutableDictionary * deletedDic = [[NSMutableDictionary alloc]init];
    //已经删除的孩子数组
    NSMutableArray * ChildIdArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteChildArray"] != nil) {
        
        NSString* str = [user objectForKey:@"deleteChildArray"];
        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        ChildIdArr = [dict objectForKey:@"deleteChildArray"];
    }
    //已经删除的班级数组
    NSMutableArray * ClassArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteClassArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deleteClassArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        ClassArr = [dict1 objectForKey:@"deleteClassArray"];
    }
    //已经删除的测试计划数组
    NSMutableArray * PlanArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deletePlanArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deletePlanArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        PlanArr = [dict1 objectForKey:@"deletePlanArray"];
    }
    //已经删除的营销孩子数组
    NSMutableArray * MasterArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteMasterArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deleteMasterArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        MasterArr = [dict1 objectForKey:@"deleteMasterArray"];
    }
    
    //将这四个数组设置成对象
    [deletedDic setObject:PlanArr forKey:@"ProgramIdArr"];
    [deletedDic setObject:MasterArr forKey:@"MasterIdArr"];
    [deletedDic setObject:ChildIdArr forKey:@"ChildIdArr"];
    [deletedDic setObject:ClassArr forKey:@"ClassArr"];
    //删除的对象////////////////////////////////////////////////////////////////////
    
    //***************************待上传的孩子childlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadChildListArray = [[NSMutableArray alloc]init];//childlist
    for (NSMutableDictionary * dict in localChildListArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadChildListArray addObject:dict];
        }
    }
    //待上传的孩子childlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的班级classlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadClassListArray = [[NSMutableArray alloc]init];//classlist
    for (NSMutableDictionary * dict in localClassListArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadClassListArray addObject:dict];
        }
    }
    //待上传的班级classlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的测试计划programlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadProgramsArray = [[NSMutableArray alloc]init];//program
    for (NSMutableDictionary * dict in localProgramsArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadProgramsArray addObject:dict];
        }
    }
    //待上传的测试计划programlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的测试结果result////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadTestResultArray = [[NSMutableArray alloc]init];//masterDetail
    for (NSMutableDictionary * dict in localTestResultArray) {
        NSMutableDictionary * masterdic = [dict objectForKey:@"master"];
        NSMutableArray * detailArr = [dict objectForKey:@"detailList"];
        NSMutableDictionary * newDICTIONARY = [[NSMutableDictionary alloc]init];
        int a = 0;
        //先判断MASTER
        NSInteger dictid =[[masterdic objectForKey:@"Id"]integerValue];
        if (dictid<0 || [masterdic objectForKey:@"1900V"] !=nil) {
            a+=1;
        }else{//master没有更新的话， 判断与之对应的detail
            for (NSMutableDictionary * detailDic in detailArr) {
                NSInteger dictid =[[detailDic objectForKey:@"Id"]integerValue];
                if (dictid<0 || [detailDic objectForKey:@"1900V"] !=nil) {
                    a+=1;
                }
            }
        }
        if (a!=0) {
            [newDICTIONARY setObject:masterdic forKey:@"ResultMaster"];
            [newDICTIONARY setObject:detailArr forKey:@"ResultDetail"];
            [readyToLoadTestResultArray addObject:newDICTIONARY];
        }
    }
    if (readyToLoadTestResultArray.count ==0) {
        //没有任何修改  给空数组和空字典
        NSMutableDictionary * dic1= [[NSMutableDictionary alloc]init];
        NSMutableArray * arr1 = [[NSMutableArray alloc]init];
        NSMutableDictionary * newDICTIONARY = [[NSMutableDictionary alloc]init];
        [newDICTIONARY setObject:dic1 forKey:@"ResultMaster"];
        [newDICTIONARY setObject:arr1 forKey:@"ResultDetail"];
        [readyToLoadTestResultArray addObject:newDICTIONARY];
    }
    //待上传的结果result////////////////////////////////////////////////////////////////////
    
    
    //**********************************************************************************************************************************//
    //**********************************************************************************************************************************//
    //**********************************************************************************************************************************//
    //开始上传
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        /////////////////////请求
        //菊花
        self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
        //    self.HUD.mode = MBProgressHUDModeIndeterminate;
        //     self.HUD.opacity = 1;
        self.HUD.color = [UIColor whiteColor];
        self.HUD.dimBackground = YES;
        //设置菊花颜色  只能设置菊花的颜色
        self.HUD.activityIndicatorColor = [UIColor redColor];
        [self.view addSubview:self.HUD];
        [self.HUD showAnimated:YES];
        NSString * urls = @"/upload/testresult";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSLog(@"%@",url);
        //        NSString * kuohao = @"[]";
        NSNumber * aId= [NSNumber numberWithInteger:agencyId];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
        //设置参数
        NSData * datachild = [NSJSONSerialization dataWithJSONObject:readyToLoadChildListArray options:0  error:nil];
        NSString * jsStrchild = [[NSString alloc]initWithData:datachild encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrchild1 = [self stringCutN:jsStr];
        
        NSData * dataclass = [NSJSONSerialization dataWithJSONObject:readyToLoadClassListArray options:0  error:nil];
        NSString * jsStrclass = [[NSString alloc]initWithData:dataclass encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrclass1 = [self stringCutN:jsStr];
        
        NSData * datapro = [NSJSONSerialization dataWithJSONObject:readyToLoadProgramsArray options:0  error:nil];
        NSString * jsStrpro = [[NSString alloc]initWithData:datapro encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrpro1 = [self stringCutN:jsStr];
        
        NSData * dataresult = [NSJSONSerialization dataWithJSONObject:readyToLoadTestResultArray options:0  error:nil];
        NSString * jsStrresult = [[NSString alloc]initWithData:dataresult encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //        NSString *  jsStrresult1 = [self stringCutN:jsStr];
        
        NSData *jsonDataPrama = [NSJSONSerialization dataWithJSONObject:deletedDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStringDic;
        jsonStringDic = [[NSString alloc]initWithData:jsonDataPrama encoding:NSUTF8StringEncoding];
        NSString *  useFulString1 = [self stringCutN:jsonStringDic];
        
        NSDictionary * parama = @{@"ServiceUnitId":aId,@"JsonChildList":jsStrchild,@"JsonClassList":jsStrclass,@"JsonProgramList":jsStrpro,@"JsonTestResult":jsStrresult,@"JsonDeleteObj":useFulString1};
        
        //            NSData * Pramadata = [NSJSONSerialization dataWithJSONObject:parama options:NSJSONWritingPrettyPrinted error:nil];
        //            NSString * pramaDic;
        //            pramaDic = [[NSString alloc]initWithData:Pramadata encoding:NSUTF8StringEncoding];
        //        NSString *  prama1 = [self stringCutN:pramaDic];
        ////
        //
        manager.requestSerializer.timeoutInterval = 30;
        [manager POST:url parameters:parama progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"上传大数据 success");
            NSMutableDictionary *relationDict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSMutableDictionary * newoldDic =[relationDict objectForKey:@"DeleteIdRelation"];//新旧关系
            
            NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            [user removeObjectForKey:@"deleteChildArray"];
            [user removeObjectForKey:@"deleteClassArray"];
            [user removeObjectForKey:@"deletePlanArray"];
            [user removeObjectForKey:@"deleteMasterArray"];
            /**********************************************************************************************************************************/
            //清除新数据的负数ID 和 1900V 改变字段
            //***************************待上传的孩子childlist////////////////////////////////////////////////////////////////////
            NSMutableArray * childNewOld = [newoldDic objectForKey:@"ChildIdRelation"];
            for (NSMutableDictionary * dict in localChildListArray.reverseObjectEnumerator) {
                if ( [dict objectForKey:@"1900V"] !=nil) {
                    [dict removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * childNewoldDic in childNewOld) {
                    if ([[dict objectForKey:@"Id"]isEqual:[childNewoldDic objectForKey:@"OldId"]] ) {
                        [dict removeObjectForKey:@"Id"];
                        [dict setObject:[childNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                }
            }
            //待上传的孩子childlist////////////////////////////////////////////////////////////////////
            
            //***************************待上传的班级classlist////////////////////////////////////////////////////////////////////
            NSMutableArray * classNewOld = [newoldDic objectForKey:@"ClassIdRelation"];
            for (NSMutableDictionary * dict in localClassListArray.reverseObjectEnumerator) {
                if ([dict objectForKey:@"1900V"] !=nil) {
                    [dict removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * classNewoldDic in classNewOld) {
                    if ([[dict objectForKey:@"Id"]isEqual:[classNewoldDic objectForKey:@"OldId"]] ) {
                        [dict removeObjectForKey:@"Id"];
                        [dict setObject:[classNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                }
            }
            //待上传的班级classlist////////////////////////////////////////////////////////////////////
            
            //***************************待上传的测试计划programlist////////////////////////////////////////////////////////////////////
            NSMutableArray * programNewOld = [newoldDic objectForKey:@"ProgramIdRelation"];
            for (NSMutableDictionary * dict in localProgramsArray.reverseObjectEnumerator) {
                if ([dict objectForKey:@"1900V"] !=nil) {
                    [dict removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * programNewoldDic in programNewOld) {
                    if ([[dict objectForKey:@"Id"]isEqual:[programNewoldDic objectForKey:@"OldId"]] ) {
                        [dict removeObjectForKey:@"Id"];
                        [dict setObject:[programNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                    
                }
            }
            //待上传的测试计划programlist////////////////////////////////////////////////////////////////////
            
            //***************************待上传的测试结果result////////////////////////////////////////////////////////////////////
            NSMutableArray * masterNewOld = [newoldDic objectForKey:@"MasterIdRelation"];
            NSMutableArray * detailNewOld = [newoldDic objectForKey:@"DetailIdRelation"];
            for (NSMutableDictionary * dict in localTestResultArray.reverseObjectEnumerator) {
                NSMutableDictionary * masterdic = [dict objectForKey:@"master"];
                NSMutableArray * detailArr = [dict objectForKey:@"detailList"];
                //先判断MASTER
                if ([masterdic objectForKey:@"1900V"] !=nil) {
                    [masterdic removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * masterNewoldDic in masterNewOld) {
                    if ([[masterdic objectForKey:@"Id"]isEqual:[masterNewoldDic objectForKey:@"OldId"]] ) {
                        [masterdic removeObjectForKey:@"Id"];
                        [masterdic setObject:[masterNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                }
                //master没有更新的话， 判断与之对应的detail
                for (NSMutableDictionary * detailDic in detailArr.reverseObjectEnumerator) {
                    if ([detailDic objectForKey:@"1900V"] !=nil) {
                        [detailDic removeObjectForKey:@"1900V"];
                    }
                    for (NSMutableDictionary * detailNewoldDic in detailNewOld) {
                        if ([[detailDic objectForKey:@"Id"]isEqual:[detailNewoldDic objectForKey:@"OldId"]] ) {
                            [detailDic removeObjectForKey:@"Id"];
                            [detailDic setObject:[detailNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                        }
                    }
                    
                }
                
            }
            //待上传的结果result////////////////////////////////////////////////////////////////////
            /**********************************************************************************************************************************/
            
            //将新孩子的负数ID替换? 营销场景
            if ([user objectForKey:@"finalSaleDic"]!=nil) {
                
                NSString * FS = [user objectForKey:@"finalSaleDic"];
                NSData * jsonData = [FS dataUsingEncoding:NSUTF8StringEncoding];
                NSMutableDictionary * mdic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray * masterIdArray = [mdic objectForKey:@"finalSaleDic"];
                NSMutableDictionary * newIDDic = [relationDict objectForKey:@"DeleteIdRelation"];//全部关系
                NSMutableArray * newIdArray = [newIDDic objectForKey:@"MasterIdRelation"];//MASTER关系
                
                //循环遍历 替换负数ID
                for ( NSNumber * oldId in masterIdArray.reverseObjectEnumerator) {
                    for (NSMutableDictionary * dic in newIdArray) {
                        if ([oldId isEqual:[dic objectForKey:@"OldId"]]) {
                            [masterIdArray removeObject:oldId];
                            [masterIdArray addObject:[dic objectForKey:@"NewId"]];
                        }
                    }
                }
                
                [mdic removeObjectForKey:@"finalSaleDic"];
                [mdic setObject:masterIdArray forKey:@"finalSaleDic"];
                
                NSData * dataDic = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:nil];
                NSString * FSS = [[NSString alloc]initWithData:dataDic encoding:NSUTF8StringEncoding];
                //
                
                [user removeObjectForKey:@"finalSaleDic"];
                [user setObject:FSS forKey:@"finalSaleDic"];
                
                [user synchronize];
            }
            [self reloadAllData];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"上传大数据 error");
            NSError * err = error;
            [self showMessage:@"同步失败，请稍后重试"];
            NSLog(@"登陆因为这个失败了%@",err.description);
            [self.HUD removeFromSuperview];
            self.HUD = nil;
        }];
    }
    
}

#pragma mark
#pragma mark 同步数据
-(void)reloadAllData{
    NSLog(@"开始同步");
    //检测网络
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        NSString * urls = @"/upload/testresult";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSString * kuohao =@"[]";
        NSDictionary *parama = @{@"ServiceUnitId":[user objectForKey:@"AgencyId"],@"ChildList":kuohao,@"ClassList":kuohao,@"ProgramList":kuohao};
        [[HttpRequest sharedInstance] postWithURLString:url parameters:parama success:^(id responseObject) {
            NSLog(@"更新成功");
            self.testDataChangedLabel.hidden = YES;
            
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            //将未分班放在最后
            NSMutableArray * classArray=[NSMutableArray array];
            classArray = [dict objectForKey:@"ClassList"];
            NSDictionary * unClassed = [[NSDictionary alloc]init];
            for (NSDictionary*dic in classArray.reverseObjectEnumerator) {
                if ([[dic objectForKey:@"Name"]isEqualToString:@"未分班"]) {
                    unClassed = dic;
                    [classArray removeObject:dic];
                    
                }
            }
            //        [classArray insertObject:unClassed atIndex:0];
            [classArray addObject:unClassed];
            [dict removeObjectForKey:@"ClassList"];
            [dict setObject:classArray forKey:@"ClassList"];
            NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            NSString * allstr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            //
            [user removeObjectForKey:@"AllData"];
            [user setObject:allstr forKey:@"AllData"];
            [user synchronize];
            [self showMessage:@"同步成功"];
            
            
        } failure:^(NSError *error) {
            [self showMessage:@"同步失败，请稍后再试"];
            [self.HUD removeFromSuperview];
            self.HUD = nil;
        }];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
